# -*- coding: utf-8 -*-

import time
import hashlib
import requests
import urllib
import random
import json

class ubnk():
    user_agent_list = ["Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/61.0",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
                    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
                    "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",
                    ]
    _headers = {
#    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Type': 'application/json',
	'Accept': 'application/json',
    }
    _headers['User-Agent'] = random.choice(user_agent_list)
    
    def __init__(self, api_Key, secret_key):
#        self.url = 'https://api.ubex.one'
        self.url = 'https://service.ubex.one'
        self.api_Key = api_Key
        self.secret_key = secret_key
    
    def sign(self,params,key):
        raw = '';
        params = sorted(params.items(), key=lambda a: a[0])
        for item in params:
            raw += str(item[0]) + str(item[1])
        hash = hashlib.md5()
        hash.update((raw + key).encode('utf-8'))
        return hash.hexdigest()

    def get(self,url,params):
        headers = dict(self._headers)
#        postdata = urllib.parse.urlencode(params)
        postdata = json.dumps(params)
        try:
            response = requests.get(url, postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  0 :
                    print(data.get('msg'),data.get('code'))
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
    def post(self,url,params):
        headers = dict(self._headers)
#        postdata = urllib.parse.urlencode(params)
        postdata = json.dumps(params)
        try:
            response = requests.post(url, postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  0 :
                    print(data.get('msg'),data.get('code'))
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
    def get_sign(self,url,params):
        headers = dict(self._headers)
#        postdata = urllib.parse.urlencode(params)
        postdata = json.dumps(params)
        try:
            response = requests.get(url, postdata, headers=headers, timeout=5)
            # print(response.status_code)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  0 :
                    print(data.get('msg'),data.get('code'))
                return data.get('data')

            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
        
    def postt(self,url,params):
        headers = dict(self._headers)
#        postdata =urllib.parse.urlencode(params)
        postdata = json.dumps(params)
        try:
            response = requests.post(url,postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  0 :
                    print(data.get('msg'),data.get('code'))
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
    
    def get_balance(self):
        dit = {
            "api_key": self.api_Key,
            "time": int(time.time())
        }
        dit["sign"] = self.sign(dit,self.secret_key)
        url =self.url + '/open/api/user/account'
        return self.get_sign(url,dit) 

    def get_depth(self,coin,quote_unit,side):
        dit={'side':side,
            'coin':coin,
            'quote_unit':quote_unit,
            'isReverse':'false',
                }
#        url =self.url + '/open/api/market_dept'
        url = 'https://service.ubex.one:8080/matchservice/dept/list'
        return self.post(url,dit)
    
    def take_order(self,side,coin,quote_unit,price,quantity):
        dit = {
            'side':side,
            'exec_type':'Limit',
            'price':price,
            'quantity':quantity,
        }
        ditt={'coin':coin,
            'quote_unit':quote_unit,
             'api_key':self.api_Key,
            'time':int(time.time()),
                }
        dit["sign"] = self.sign(ditt,self.secret_key)
#        url =self.url + '/open/api/create_order'
        url = 'https://service.ubex.one:8080/matchservice/open/create_order'
        dit = dict(dit,**ditt)
        return self.postt(url,dit)
    
    def get_ticker(self,coin,quote_unit):
        params={}
        params['coin']=coin
        params['quote_unit']=quote_unit
        url =self.url + '/open/api/get_ticker'
#        url = 'https://service.ubex.one:8080/matchservice/open/get_ticker'
        return self.post(url,params)
    def get_allticker(self):
        params={}
#        params['coin']=coin
#        params['quote_unit']=quote_unit
        url =self.url + '/open/api/get_trades'
#        url = 'https://service.ubex.one:8080/matchservice/open/get_ticker'
        return self.get(url,params)
    def cancel_order(self,idd):
        dit = {
            'id':idd,
            'api_key':self.api_Key,
            'time':int(time.time()),
        }
        dit["sign"] = self.sign(dit,self.secret_key)
#        url =self.url + '/open/api/cancel_order'
        url = 'https://service.ubex.one:8080/matchservice/open/cancel_order'
        return self.postt(url,dit)

    def cancel_all_order(self,coin,quote_unit):
        dit = {
            'coin':coin,
            'quote_unit':quote_unit,
            'api_key':self.api_Key,
            'time':int(time.time()),
        }
        dit["sign"] = self.sign(dit,self.secret_key)
        url =self.url + '/open/api/cancel_order_all'
        return self.postt(url,dit)


    def get_pp(self):
        dit={}
        url =self.url + '/open/api/common/symbols'
        return self.get(url,dit)

        



















'''
import hashlib
import time
import requests

def gen_sign(params,key):
  raw = '';
  params = sorted(params.items(), key=lambda a: a[0])
  for item in params:
    raw += str(item[0]) + str(item[1])

  hash = hashlib.md5()
  hash.update((raw + key).encode('utf-8'))
  return hash.hexdigest()

app_key = '202005210261653376'
app_secret = 'fa0516e5e1ef3034ca5c832739a9da37'
api_url = 'https://api.ubex.one'
endpoint = '/open/api/user/account'

params = {
    'api_key': app_key,
    'time': int(time.time())
}

sign = gen_sign(params, app_secret)

params['sign'] = sign

headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

print(params)
req = requests.request('GET', api_url + endpoint, params=params, headers=headers)
print(req.request.url)
res = req.json()

print(res)
'''